package com.aek.aekdroid;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.aek.aekdroid.data.IDbConstants;
import com.aek.aekdroid.data.MatchData;

import eu.erikw.PullToRefreshListView;

public class ScheduleActivity extends BaseActivity {
	PullToRefreshListView listMatches;
	private TextView emptyList;
	private Spinner selectTour;
	private Cursor cursor;
	private SimpleCursorAdapter adapter;
	public static final String TAG = "ScheduleActivity";
	static final String[] FROM = { MatchData.MATCHES_C_HOME_TEAM, MatchData.MATCHES_C_AWAY_TEAM, MatchData.MATCHES_C_HOME_GOALS,
			MatchData.MATCHES_C_AWAY_GOALS, MatchData.MATCHES_C_STADIUM, MatchData.MATCHES_C_DATETIME, MatchData.MATCHES_C_TOURNAMENT,
			MatchData.MATCHES_C_CHANNEL };
	static final int[] TO = { R.id.match_homeTeam, R.id.match_awayTeam, R.id.match_homeGoals, R.id.match_awayGoals, R.id.match_stadium,
			R.id.match_datetime, R.id.match_tournament, R.id.match_channel };
	public static final String NEW_UPDATES = "com.aek.aekdroid.NEW_UPDATES";
	public static final String APP_UPDATE = "com.aek.aekdroid.APP_UPDATE";
	public static final String SEND_NOTIFICATIONS = "com.aek.aekdroid.SEND_NOTIFICATIONS";
	private ScheduleReceiver scheduleReceiver;
	private VersionReceiver versionReceiver;
	private IntentFilter scheduleFilter;
	private IntentFilter versionFilter;
	private TextView schedule_title;
	private int backButtonCount;
	static int prevId = -1;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		prevId = getIntent().getIntExtra(IDbConstants.MATCHES_C_ID, -1);
		Configuration c = getResources().getConfiguration();
		this.setTitle(getString(R.string.app_name) + " " + getString(R.string.app_version));
		// FirstTime
		// if (aek.getPrefs().getString(getString(R.string.pref_updateFreqKey),
		// null) == null) {
		Eula.show(this);
		// Intent intent = new Intent(this, PrefsActivity.class);
		// intent.putExtra("firstTime", true);
		// startActivity(intent);
		// Toast.makeText(this, R.string.pref_init, Toast.LENGTH_LONG).show();
		// }
		setContentView(R.layout.schedule);
		// Helper.setAlarm(TAG, getApplicationContext(), -1);
		scheduleReceiver = new ScheduleReceiver();
		versionReceiver = new VersionReceiver();
		scheduleFilter = new IntentFilter(NEW_UPDATES);
		versionFilter = new IntentFilter(APP_UPDATE);
		listMatches = (PullToRefreshListView) findViewById(R.id.schedule_ListMatches);
		emptyList = (TextView) findViewById(R.id.schedule_emptyList);
		selectTour = (Spinner) findViewById(R.id.schedule_tournament);
		// this.setUpList();
		listMatches.setOnItemClickListener(new ScheduleClickListener(this));
		listMatches.setOnRefreshListener(new MatchRefreshListener(this));
		OnItemSelectedListener selectTourListener = new TourListener();
		selectTour.setOnItemSelectedListener(selectTourListener);
		schedule_title = (TextView) findViewById(R.id.schedule_title);
		schedule_title.setText(schedule_title.getText() + " " + aek.getPeriod());
		setUpList();
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		if (aek.isAdmin()) {
			super.onCreateContextMenu(menu, v, menuInfo);
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.schedule_menu, menu);
			if (v.getId() == R.id.schedule_emptyList) {
				menu.removeItem(R.id.schedule_menu_addDetails);
				menu.removeItem(R.id.schedule_menu_delete);
				menu.removeItem(R.id.Schedule_menu_startingEleven);
				menu.removeItem(R.id.schedule_menu_edit);
			}

		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		int _id = -1;
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		if (info != null) {
			Cursor match = (Cursor) listMatches.getItemAtPosition(info.position);
			_id = match.getInt(match.getColumnIndex(IDbConstants.MATCHES_C_ID));
			match.close();
		}
		if (item.getItemId() == R.id.schedule_menu_create) {
			Intent createMatchIntent = new Intent(this, CreateMatchActivity.class);
			createMatchIntent.putExtra(CreateMatchActivity.MATCH_ID, -1);
			startActivity(createMatchIntent);
			return true;
		} else if (item.getItemId() == R.id.schedule_menu_edit) {
			Intent editMatchIntent = new Intent(this, CreateMatchActivity.class);
			editMatchIntent.putExtra(CreateMatchActivity.MATCH_ID, _id);
			startActivity(editMatchIntent);
			return true;
		} else if (item.getItemId() == R.id.schedule_menu_addDetails) {
			Intent addDetailsIntent = new Intent(this, AddDetailsActivity.class);
			addDetailsIntent.putExtra(AddDetailsActivity.MATCH_ID, _id);
			addDetailsIntent.putExtra(AddDetailsActivity.DETAIL_ID, -1);
			startActivity(addDetailsIntent);
			return true;
		} else if (item.getItemId() == R.id.Schedule_menu_startingEleven) {
			Intent addElevenIntent = new Intent(this, AddElevenActivity.class);
			addElevenIntent.putExtra(AddElevenActivity.MATCH_ID, _id);
			startActivity(addElevenIntent);
			return true;
		} else if (item.getItemId() == R.id.schedule_menu_delete) {
			Intent deleteIntent = new Intent(this, DeleteActivity.class);
			deleteIntent.putExtra(DeleteActivity.MATCH_ID, _id);
			deleteIntent.putExtra(DeleteActivity.TYPE, DeleteActivity.MATCH);
			startActivity(deleteIntent);
			return true;
		} else {
			return super.onContextItemSelected(item);
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		cursor.close();
		aek.getMatchData().close();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.removeItem(R.id.menu_schedule);
		menu.removeItem(R.id.menu_checkUpdate);
		return true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		this.setUpList();
		if (aek.isAdmin()) {
			registerForContextMenu(listMatches);
			registerForContextMenu(emptyList);
		}
		registerReceiver(scheduleReceiver, scheduleFilter, SEND_NOTIFICATIONS, null);
		registerReceiver(versionReceiver, versionFilter, SEND_NOTIFICATIONS, null);
	}

	@Override
	protected void onPause() {
		super.onPause();
		cursor.close();
		aek.getMatchData().close();
		if (aek.isAdmin()) {
			unregisterForContextMenu(listMatches);
			unregisterForContextMenu(emptyList);
		}
		unregisterReceiver(scheduleReceiver);
		unregisterReceiver(versionReceiver);
	}

	@Override
	public void onBackPressed() {
		if (backButtonCount >= 1) {
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_HOME);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		} else {
			Toast.makeText(this, R.string.exitApp, Toast.LENGTH_SHORT).show();
			backButtonCount++;
		}
	}

	private void setUpList() {
		cursor = aek.getMatchData().getMatches();
		if (cursor.getCount() > 0) {
			emptyList.setVisibility(View.GONE);
		}
		// startManagingCursor(cursor);
		// Setup Adapter
		adapter = new SimpleCursorAdapter(this, R.layout.match, cursor, FROM, TO);
		adapter.setViewBinder(new Binder());
		listMatches.setAdapter(adapter);
		MyLog.d(TAG, "Getting current match");
		listMatches.setSelection(getCurrentMatch());
	}

	private int getCurrentMatch() {

		long now = System.currentTimeMillis();
		for (int i = 0; i < listMatches.getCount(); i++) {
			Cursor data = (Cursor) listMatches.getItemAtPosition(i);
			if (data == null) {
				continue;
			}
			if (prevId == -1) {
				long datetime = data.getLong(data.getColumnIndex(IDbConstants.MATCHES_C_DATETIME));
				if (datetime < now) {
					return i - 1;
				}
			} else {
				int id = data.getInt(data.getColumnIndex(IDbConstants.MATCHES_C_ID));
				if (id == prevId) {
					return i;
				}
			}

		}

		return 0;
	}

	class TourListener implements OnItemSelectedListener {

		@Override
		public void onItemSelected(AdapterView<?> adapter, View view, int pos, long row) {
			String tournament = (String) adapter.getItemAtPosition(pos);
			MyLog.d(TAG, "Changing tournament to " + tournament);
			MatchData.tournament = tournament;
			ScheduleActivity.this.setUpList();
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {

		}

	}

	// View binder constant to inject business logic for timestamp to relative
	// time conversion
	class Binder implements ViewBinder {

		@Override
		public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
			if (view.getId() == R.id.match_datetime) {
				long timestamp = cursor.getLong(columnIndex);
				((TextView) view).setText(Helper.createDate(timestamp));
				return true;
			} else if (view.getId() == R.id.match_channel) {
				String img = String.valueOf(cursor.getString(columnIndex));
				if (img.equals("-")) {
					img = "notv";
				}
				img = img.replaceAll(" ", "").toLowerCase();
				int r = ScheduleActivity.this.aek.getResources().getIdentifier(img, "drawable", "com.aek.aekdroid");
				((ImageView) view).setImageResource(r);
				return true;
			} else {
				return false;
			}

		}

	}

	class VersionReceiver extends BroadcastReceiver {
		public static final String TAG = "ScheduleReceiver";

		@Override
		public void onReceive(Context context, Intent intent) {
			String version = intent.getStringExtra(UpdateChecker.NEW_VERSION);
			boolean manual = intent.getBooleanExtra(MatchUpdaterService.MANUAL, false);
			String mess;
			if (version != null) {
				mess = getString(R.string.msgVersionUpdate, version);
			} else {
				mess = getString(R.string.msgNoVersionUpdate, version);
			}
			if (manual) {
				Toast.makeText(aek, mess, Toast.LENGTH_SHORT).show();
			}
			MyLog.d(TAG, "onReceive " + version);
		}

	}

	class ScheduleReceiver extends BroadcastReceiver {
		public static final String TAG = "ScheduleReceiver";

		@Override
		public void onReceive(Context context, Intent intent) {
			int updates = intent.getIntExtra(MatchUpdaterService.NEW_UPDATES_COUNT, -1);
			String mess;
			boolean manual = intent.getBooleanExtra(MatchUpdaterService.MANUAL, false);
			MyLog.d(TAG, "onReceive " + updates + " , manual:" + manual);
			if (updates > 0) {
				setUpList();
				mess = getString(R.string.msgUpdates, updates);
				ScheduleActivity.this.updateCalendar();
			} else if (updates == 0) {
				mess = getString(R.string.msgNoUpdates);
			} else {
				mess = getString(R.string.msgNoInternetConnection);
			}
			if (manual) {
				MyLog.d(TAG, "Showing toast about updates");
				ScheduleActivity.this.listMatches.onRefreshComplete();
				Toast.makeText(getApplicationContext(), mess, Toast.LENGTH_SHORT).show();
			}
			MyLog.d(TAG, "onReceive " + updates + " , manual:" + manual);
		}
	}

	private void updateCalendar() {
		Calendar cal = new Calendar(this);
		cal.updateCalendar(aek);
	}

	class ScheduleClickListener implements OnItemClickListener {
		public static final String TAG = "ScheduleListener";
		private ScheduleActivity sa;

		public ScheduleClickListener(ScheduleActivity sa) {
			this.sa = sa;
		}

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) {
			Cursor match = (Cursor) listMatches.getItemAtPosition(pos);
			int _id = match.getInt(match.getColumnIndex(IDbConstants.MATCHES_C_ID));
			match.close();
			Intent showMatchIntent = new Intent(sa, ShowMatchActivity.class);
			showMatchIntent.putExtra(IDbConstants.MATCHES_C_ID, _id);
			startActivity(showMatchIntent);

		}

	}

}